﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Model;
using Controller;
using Common;

namespace CodeFactory
{
   
    public partial class ControlSelector : Form
    {
        #region 私有字段
        
        private List<string> ControlTypeState;
        private string ConfigName;
        private List<exFieldControlInfo> list;
        private MainStudio mainStudio;
        #endregion


        #region 属性
        private ControlSelectorBO _csBO;
        public ControlSelectorBO csBO
        {
            get
            {
                if (_csBO == null)
                      _csBO = FactoryControllerBO.CurrentFA.CreateContorlSelectorBOInstance();
                return _csBO; 
            }
           
        }
        #endregion
        

        #region 初始化方法
        
        public ControlSelector()
        {
            InitializeComponent();
           
        }
        
        public ControlSelector(string configname,MainStudio _mainStudio)
        {
            InitializeComponent();
            ConfigName = configname;
            list=csBO.GetFieldToControlList(ConfigName);
            BindBaseTypeComboBoxData();
            mainStudio = _mainStudio;
        }
        
        private void ControlSelector_Load(object sender, EventArgs e)
        {
            try
            {
                GridViewDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        
        #region 私有方法
        /// <summary>
        /// 获取控件种类选取的状态
        /// </summary>
        /// <returns></returns>
        private List<string> GetControlTypeState()
        {
            ControlTypeState = new List<string>();
            if (chkWinform.Checked)
            {
                ControlTypeState.Add("WinForm");
            }
            else
            {
                if (ControlTypeState.Contains("WinForm"))
                {
                    ControlTypeState.Remove("WinForm");
                }
            }
            if (chkDev.Checked)
            {
                ControlTypeState.Add("DevExpress");
            }
            else
            {
                if (ControlTypeState.Contains("DevExpress"))
                {
                    ControlTypeState.Remove("DevExpress");
                }
            }
            if (chkWebfrom.Checked)
            {
                ControlTypeState.Add("WebForm");
            }
            else
            {
                if (ControlTypeState.Contains("WebForm"))
                {
                    ControlTypeState.Remove("WebForm");
                }
            }
            return ControlTypeState;
        }

        /// <summary>
        /// 数据表数据绑定事件
        /// </summary>
        private void GridViewDataBind()
        {
            try
            {
                dataGridView1.Rows.Clear();
                list.ForEach(exFIC =>
                {
                    DataGridViewRow dr = new DataGridViewRow();
                    dr.CreateCells(dataGridView1);
                    //生成控件下拉菜单列
                    DataGridViewComboBoxCell cb = new DataGridViewComboBoxCell();
                    evComboItem comb = null;
                    exFIC.ControlList.ForEach(ci =>
                    {
                        if (GetControlTypeState().Contains(ci.ControlClass))
                        {
                            comb = new evComboItem
                            {
                                Class = ci.ControlClass,
                                Value = ci.Prefix,
                                Text = ci.ControlType
                            };
                            cb.Items.Add(comb);
                            cb.ValueMember = "Value";
                            cb.DisplayMember = "Text";
                        }
                    });
                    dr.Cells[0].Value = exFIC.FieldName;
                    dr.Cells[1].Value = exFIC.FieldType;
                    dr.Cells[2] = cb;
                    dr.Cells[2].Style.NullValue = comb == null ? "" : comb.Text;
                    //设置单元格的默认值，该comb为配置文件项的最后一个配置项
                    dr.Cells[3].Value = (comb == null ? "" : comb.Value) + exFIC.FieldName;
                    dr.Cells[4].Value = exFIC.FieldDescription;
                    dataGridView1.Rows.Add(dr);
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 绑定基底种类
        /// </summary>
        private void BindBaseTypeComboBoxData()
        { 
           foreach(string s in Enum.GetNames(typeof(enumBaseControlType)))
            {
                cmbBaseControl.Items.Add(s);
            }
           cmbBaseControl.SelectedIndex = cmbBaseControl.Items.Count-1;//绑定最后一项，因为DevUserControl在最后一个
        }

        /// <summary>
        /// 获得所有生成必须的数据
        /// </summary>
        private exFullInfoForBuild GetAllInfoForBuild()
        {
            exFullInfoForBuild exInfo = new exFullInfoForBuild();
            exInfo.BaseControlType = (enumBaseControlType)Enum.Parse(typeof(enumBaseControlType), cmbBaseControl.SelectedItem.ToString());
            exInfo.IsBuildAllFieldAsNewTable = chkBuildTable.Checked;
            exInfo.IsBuildDevLayout = chkBuildLayout.Checked;
            List<exFullInfoForBuildChild> list = new List<exFullInfoForBuildChild>();
            for (int i = 0; i < dataGridView1.Rows.Count;i++)
            {   exFullInfoForBuildChild exInfoChild = new exFullInfoForBuildChild();
                for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
                {
                    
                    if (j == 0)
                    { exInfoChild.FieldName = dataGridView1.Rows[i].Cells[j].Value.ToString();}
                    if (j == 1)
                    { exInfoChild.FieldType = dataGridView1.Rows[i].Cells[j].Value.ToString(); }
                    if (j == 2)
                    {   
                        string[] s=dataGridView1.Rows[i].Cells[j].FormattedValue.ToString().Split('-');
                        exInfoChild.ControlClass =s[0];
                        exInfoChild.ControlName = s[1];
                    }
                    if (j == 3)
                    { exInfoChild.BuildName = dataGridView1.Rows[i].Cells[j].Value.ToString(); }
                    if (j == 4)
                    {
                        exInfoChild.LayoutText = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                }
                list.Add(exInfoChild);
            }
            exInfo.list = list;
            return exInfo;
        }

        /// <summary>
        /// 判断重复项
        /// </summary>
        /// <returns></returns>
        private bool HasRepeatName()
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                int num = 0;
                for (int j = 0; j < dataGridView1.Rows.Count; j++)
                {
                    if (dataGridView1.Rows[i].Cells[3].Value.ToString() == dataGridView1.Rows[j].Cells[3].Value.ToString())
                    {
                        num++;
                    }
                }
                if (num > 1)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion


        #region 控件事件

        private void chkWinform_CheckedChanged(object sender, EventArgs e)
        {
            GridViewDataBind();
        }

        private void chkDev_CheckedChanged(object sender, EventArgs e)
        {
            GridViewDataBind();
        }

        private void chkWebfrom_CheckedChanged(object sender, EventArgs e)
        {
            GridViewDataBind();
        }

        /// <summary>
        /// 用于处理控件种类下拉Combobox的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
           if(e.Control.GetType()==typeof(DataGridViewComboBoxEditingControl))
           {
               ComboBox cb = (ComboBox)e.Control;
               if (cb != null)
                {

                   // 首先移除事件处理程序以防止多重触发附加事件
                   cb.SelectedIndexChanged -= ComboBox_SelectedIndexChanged;

                   // 附加事件处理程序
                   cb.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
                }
           }
        }

        /// <summary>
        /// 用于处理控件种类下拉Combobox的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cb = (ComboBox)sender;
            try
            {
                evComboItem ci = (evComboItem)cb.SelectedItem;
                object fieldName = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value;
                dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex + 1].Value = ci.Value + fieldName;
        
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 防止重复名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 3)
                return;
            int num = 0;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (String.Compare(
                     dataGridView1.Rows[i].Cells[e.ColumnIndex].Value.ToString(), 
                     dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), 
                              false) == 0)
                {
                    num++;
                }
            }
            if (num > 1)
            {
                MessageBox.Show("已有相同名称，请返回修改！");
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value + "_new";
            }
        }
        #endregion


        #region 按钮事件

        private void menuBtnBuild_Click(object sender, EventArgs e)
        {
            if (HasRepeatName())
            {
                MessageBox.Show("含有重复名称，请返回修改");
                return;
            }
           exFullInfoForBuild exFInfo = GetAllInfoForBuild();
           if (chkBuildLayout.Checked)
           {
               mainStudio.AddBuildInfoToTree(exFInfo,true);
           }
           else
           {
               mainStudio.AddBuildInfoToTree(exFInfo,false);
           }
            
            this.Close();
        }
  


        #endregion

        

        
        

      
       
      

        
        
    }
}
